<template>
  <div>
    <div id="box" v-drag="msg"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "hello word",
    };
  },
  created() {},
  directives: {
    drag: {
      bind(el, binding) {
        el.innerText = binding.value;

        el.onmousedown = () => {
          let event = window.event || event;
          //获取鼠标的坐标
          let x = event.clientX;
          let y = event.clientY;

          //   获取盒子偏移值
          let L = el.offsetLeft;
          let T = el.offsetTop;

          // 鼠标移动
          document.onmousemove = function (event) {
            //获取鼠标移动后的坐标
            //获取鼠标的坐标
            let x1 = event.clientX;
            let y1 = event.clientY;

            // 移动后盒子偏移值
            let l = x1 - x + L;
            let t = y1 - y + T;

            el.style.left = l + "px";
            el.style.top = t + "px";
          };
          document.onmouseup = function () {
            document.onmousemove = null;
          };
        };
      },
      rnserted() {},
    },
  },
  mounted() {},
  methods: {},
};
</script>

<style scoped lang="less">
#box {
  width: 1rem;
  height: 1rem;
  background-color: red;
  position: absolute;
  top: 0;
  left: 0;
  font-size: 0.16rem;
   user-select: none;
}
</style>


